package com.mqtt.ctwingmqtt.controller;

import com.mqtt.ctwingmqtt.domain.ResponseResult;
import com.mqtt.ctwingmqtt.domain.entity.product;
import com.mqtt.ctwingmqtt.service.ProductEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductEntityController {

    @Autowired
    private ProductEntityService productEntityService;

    // 增加
    @PostMapping("/add")
    public ResponseResult<Void> addProduct(@RequestBody product product) {
        boolean saved = productEntityService.save(product);
        if (saved) {
            return ResponseResult.success("产品添加成功", null);
        } else {
            return ResponseResult.error("产品添加失败");
        }
    }

    // 删除
    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteProduct(@PathVariable Long id) {
        boolean deleted = productEntityService.removeById(id);
        if (deleted) {
            return ResponseResult.success("产品删除成功", null);
        } else {
            return ResponseResult.error("产品删除失败");
        }
    }

    // 查询所有
    @GetMapping("/getAll")
    public ResponseResult<List<product>> getAllProducts() {
        List<product> products = productEntityService.list();
        return ResponseResult.success("查询成功", products);
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public ResponseResult<product> getProductById(@PathVariable Long id) {
        product product = productEntityService.getById(id);
        if (product != null) {
            return ResponseResult.success("查询成功", product);
        } else {
            return ResponseResult.error("产品不存在");
        }
    }

    // 修改
    @PutMapping("/{id}")
    public ResponseResult<Void> updateProduct(@PathVariable Long id, @RequestBody product product) {
        product.setId(id);
        boolean updated = productEntityService.updateById(product);
        if (updated) {
            return ResponseResult.success("产品更新成功", null);
        } else {
            return ResponseResult.error("产品更新失败");
        }
    }
}